const GET = 'GET';
const POST = 'POST';
const baseUrl = 'https://xw.psn.asia/';

const allowList = [ // 不需要登录(token)的接口
  "home/slideList",
  "home/goodsList",
  "home/goodsDetail",
  "goods/goodsCateList",
]

let loginLock = false
let bindTelLock = false
let count = 0
let pendings = [] // 等待队列 {method,url,data,success_func,err_func}

export const request = (method, url, data, success_func, error_func) => {
  new Promise((resolve, reject) => {
    let token = wx.getStorageSync('token')
    if (allowList.indexOf(url) === -1 && !token) {  // 需要登录且需要登录
      if(loginLock === false) { // 缓存中没有token,设置锁后去登录
        loginLock = true
        setTimeout(() => {
          loginLock = false
        },10000)
        pendings.push({
          method: method,
          url: url,
          data: data,
          success_func: success_func,
          error_func: error_func
        })
        wxLogin()
        reject("缓存中没有token,去登录")
      }else { // 正在登录中, 请求队列, 登录成功后再次执行
        pendings.push({
          method: method,
          url: url,
          data: data,
          success_func: success_func,
          error_func: error_func
        })
        reject("doing login ......")
      }
      return
    }
		let header = {
        'Authorization': token,
		    'content-type': 'application/x-www-form-urlencoded'
		};
		wx.request({
			url: baseUrl + url,
			method: method,
			header: header,
			data: data,
			success: (res) => {
        if(res.statusCode === 200) {
          if (res.data.code === 0) {
            resolve(res.data.data);
          }else if(res.data.code === -1 || res.data.code === -2) {
            // 请传入token或token已过期, 设置登录锁后去登录
            if(loginLock === false) {
              loginLock = true
              setTimeout(() => {
                loginLock = false
              },10000)
              wxLogin()
            }else {
              pendings.push({
                method: method,
                url: url,
                data: data
              })
              console.log("doing login ......");
            }
            reject("API token过期, 去登录")
          }else if(res.data.code === 5) {
            // 请绑定手机号, 设置登录锁后去绑定
            if(bindTelLock === false) {
              bindTelLock = true
              setTimeout(() => {
                bindTelLock = false
              },10000)
              console.log("API没有绑定手机号, 去绑定手机号");
              bindPhoneNumber()
            }
            reject("API没有绑定手机号")
          }else {
            wx.showToast({
              icon:"none",
              title: res.data.message,
            })
            console.log("未知错误...");
            reject(res.data)
          }
        }else {
          reject(res.data);
        }
			},
			fail: (err) => {
				reject(err);
			}
		})
	}).then(res => {
    success_func(res)
  }).catch(err => {
    error_func(err)
  })
}

export const wxLogin = () => {
  wx.login({
    success: res => {
      let header = {
		    'content-type': 'application/x-www-form-urlencoded'
		  };
      wx.request({
        header:header,
        method:"POST",
        url: baseUrl + 'mp/login/mpLogin',
        data:{
          code:res.code
        },
        success: res => {
          if(res.statusCode === 200) {
            if(res.data.code === 0) {
              wx.setStorageSync('token', res.data.data.token)
              // todo 如果pending队列中有接口则循环处理
              handlePending()
            }else {
              wx.showToast({
                icon:"none",
                title: res.data.message,
              })
            }
          }else {
            wx.showToast({
              icon:"none",
              title: res.data,
            })
          }
        },
        fail: err => {
          console.log("mp/mpLogin error: ",err);
        }
      })
    },
    fail: err => {
      wx.showToast({
        icon:"none",
        title: 'wx.login 失败',
      })
      console.log(err);
    }
  })
}

const handlePending = () => {
  // console.log("pendings", pendings);
  for(let i=pendings.length-1; i>=0; i--) {
    request(
      pendings[i].method,
      pendings[i].url,
      pendings[i].data,
      pendings[i].success_func,
      pendings[i].error_func,
      )
    pendings.splice(i,1)
  }
  setTimeout(() => {
    // console.log("pendings-300", pendings);
  },300)
}

export const bindPhoneNumber = () => {
  wx.setStorageSync('uid', '')

  let pages = getCurrentPages();
  let currentPage = pages[pages.length-1]
  let router = currentPage.route;
  let options = currentPage.options
  let fromPath = encodeURIComponent("/" + router + "?" + http_build_query(options))
  if(router !== 'pages/login/login') {
    wx.redirectTo({
      url: "/pages/login/login?from=" + fromPath,
    })
  }
}

export const getCount = () => {
  console.log("get count = ",count);
  // console.log("request.js get count = ",count);
  // let currentPages = getCurrentPages();
  // console.log(currentPages[currentPages.length - 1]['route']);
}

export const setCount = () => {
  count++
  console.log("set count = ",count);
  // console.log("request.js set count = ",count);
  // let currentPages = getCurrentPages();
  // console.log(currentPages[currentPages.length - 1]['route']);
}

const http_build_query = (obj) => {
  var str = [];
  for(var p in obj){
      if (obj.hasOwnProperty(p)) {
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
  }
  return str.join("&")
}
